package thread;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * pipe stream 用与在不同线程之间的直接数据传输
 */
public class PinedStreamTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        WriteData writeData=new WriteData();
        ReadData readData=new ReadData();


        PipedOutputStream out=new PipedOutputStream();
        PipedInputStream input=new PipedInputStream(out);



        Thread threadRead= new ThreadRead(readData,input);
        threadRead.start();

        Thread.sleep(1000);

        ThreadWrite threadWrite=new ThreadWrite(writeData,out);
        threadWrite.start();

        Thread.sleep(10000000);



    }

}

class WriteData{
    public  void writeMethod(PipedOutputStream out){
        try {
            System.out.println("write:");
            for (int i=0;i<300;i++){
                String outData=""+(i+1);
                out.write(outData.getBytes());
                out.flush();
                System.out.println("outData=>"+outData);
            }
            System.out.println("out 写完未关闭");
           // out.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
class ThreadWrite extends  Thread{
    private  WriteData writeData;
    private PipedOutputStream out;

    public ThreadWrite(WriteData writeData, PipedOutputStream out) {
        this.writeData = writeData;
        this.out = out;
    }

    @Override
    public void run() {
        writeData.writeMethod(out);
    }
}

class ReadData{
    public void readMethod(PipedInputStream input) throws IOException {
        System.out.println("read :");
        byte[] byteArray=new byte[20];
        int readLength=input.read(byteArray);
        while (readLength!=-1){
            String newData=new String(byteArray,0,readLength);
            System.out.println("read=>"+newData);
            readLength=input.read(byteArray);
        }
        System.out.println("read close()");
        input.close();

    }
}
class ThreadRead extends  Thread{
    private  ReadData readData;
    private PipedInputStream input;

    public ThreadRead(ReadData readData, PipedInputStream input) {
        this.readData = readData;
        this.input = input;
    }

    @Override
    public void run() {
        try {
            readData.readMethod(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}